<?php

/**
 * 应用基类控制器
 * Created by PhpStorm.
 * User: simon_min@aliyun.com
 * Date: 2016/11/5
 * Time: 14:56
 */
class Controller extends View
{
    private $var = array();

    /**
     * 构造方法
     */
    public function __construct()
    {
        if (C('SMARTY_ON')) {
            parent::__construct();
        }
        if (method_exists($this, '__init')) {
            $this->__init();
        }
        if (method_exists($this, '__auto')) {
            $this->__auto();
        }
    }

    /**
     * 获取模板路径
     * @param $tpl
     * @return string
     */
    protected function get_tpl($tpl)
    {
        if (is_null($tpl)) {
            $path = APP_TPL_PATH . '/' . CONTROLLER . '/' . ACTION . '.html';
        } else {
            $suffix = strrchr($tpl, '.');
            $tpl = empty($suffix) ? $tpl . '.html' : $tpl;
            $path = APP_TPL_PATH . '/' . CONTROLLER . '/' . $tpl;
        }
        return $path;
    }

    /**
     * 载入模板文件
     * @param null $tpl 模板文件
     */
    protected function display($tpl = NULL)
    {

        $path = $this->get_tpl($tpl);

        if (!is_file($path)) halt($path . ' 模板文件不存在！');

        if (C('SMARTY_ON')) {
            parent::display($path);
        } else {
            extract($this->var);
            include $path;
        }
    }

    /**
     * 分配模板变量
     * @param $var
     * @param $value
     */
    protected function assign($var, $value)
    {
        if (C('SMARTY_ON')) {
            parent::assign($var, $value);
        } else {
            $this->var[$var] = $value;
        }
    }

    /**
     * 成功提示方法
     * @param $msg
     * @param null $url
     * @param int $time
     */
    protected function success($msg, $url = NULL, $time = 3)
    {
        $url = $url ? "window.location.href='" . $url . "'" : 'window.history.back(-1)';
        include APP_TPL_PATH . '/success.html';
        die;
    }

    /**
     * 错误提示方法
     */
    protected function error($msg, $url = NULL, $time = 3)
    {
        $url = $url ? "window.location.href='" . $url . "'" : 'window.history.back(-1)';
        include APP_TPL_PATH . '/error.html';
        die;
    }
}